import * as React from 'react'
import { Table, Input, Button, Space, Form, InputNumber, message, Popconfirm, Row, Divider, Col, Card } from 'antd';
import { DownloadOutlined, SearchOutlined, ReloadOutlined, EditOutlined, DeleteOutlined, PlayCircleOutlined, VerticalRightOutlined } from '@ant-design/icons';
import MyModal from '../notification-table/my-modal';
import * as XLSX from 'xlsx';


export interface UniversalTableProps {
    ret?: string;
    searchKeys?: string;
    exportable?: boolean;
    pageSize?: number;
}




const UniversalTable: React.FC<UniversalTableProps> = function ({ ret, searchKeys,
    exportable, pageSize,
    ...otherProps }) {


    const [currentPage, setCurrentPage] = React.useState(1);
    const [searchTerm, setSearchTerm] = React.useState({});
    const [messageApi, contextHolder] = message.useMessage();
    const defaultMainData = [

    ]

    const [mainData, setMainData] = React.useState(defaultMainData);
    const [mainPostForm] = Form.useForm()
    const [mainUpdateForm] = Form.useForm()

    const defaultSearchKeys = 'code,name';
    let searchKeyList = searchKeys === '' ? defaultSearchKeys.split(',').map(item => item.trim()) : searchKeys.split(',').map(item => item.trim());
    //console.log(supportExport)
    console.log(searchKeyList);

    const handleExport = () => {
        const worksheet = XLSX.utils.json_to_sheet(mainData);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
        const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
        const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'table_data.xlsx';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    };

    let columns = JSON.parse(ret).columns;
    let selectedEntity = JSON.parse(ret).selectedEntity;

    //console.log(selectedEntity);

    React.useEffect(() => {
        if (selectedEntity === '') {
            setMainData(defaultMainData);
        } else {
            getMainData('http://localhost:8080/api/v1/' + selectedEntity)
        }

    }, [])





    //Api方法区 两个get 两个post 一个put 还有一个实际改变库存的方法

    //getMainData
    function getMainData(url) {
        fetch(url)
            .then(response => response.json())
            .then(data => {
                setMainData(data.data);
            })
    }

    //postMainData
    function postMainData(values: any, url) {
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(
                values
            )
        })
            .then(response => response.json())
            .then(data => {

            })
        messageApi.open({
            type: 'success',
            content: '新增成功',
        });
    }

    //putMainData
    function putMainData(values: any, url) {
        fetch(url, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(
                values
            )
        })
            .then(response => response.json())
            .then(data => {

            })
        messageApi.open({
            type: 'success',
            content: '修改成功',
        });
    }

    //deleteMainData
    function deleteMainData( url) {
        fetch(url, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            }
            
        })
            .then(response => response.json())
            .then(data => {

            })
        messageApi.open({
            type: 'success',
            content: '删除成功',
        });
    }


    //筛选功能
    const handleSearch = () => {
        //这里的查找是字符串包含 如果要完全匹配改成===
        let filteredData = mainData;

        for (var i in searchKeyList) {
            var searchKey = searchKeyList[i];
            console.log('searchKey',searchKey);
            if (searchKey === 'id')
                continue;
            if (searchTerm[searchKey]) {
                console.log('aaa')
                filteredData = filteredData.filter(item => item[searchKey].includes(searchTerm[searchKey]));
            }
        }
        //console.log(filteredData)
        setMainData(filteredData);
    }
    const resetSearch = () => {
        setSearchTerm({})
        //TODO: setMainData()
        getMainData('http://localhost:8080/api/v1/' + selectedEntity)
    }
    const SearchInput = () => {
        const handleInputChange = (key) => (e) => {
            setSearchTerm(prevState => ({
                ...prevState,
                [key]: e.target.value
            }));
            console.log(key, e.target.value);
        }
        return (
            <>
                <Space size='large'>
                    {searchKeyList.map(key => (
                        <Input
                            placeholder={"请输入" + key}
                            value={searchTerm[key]}
                            onChange={handleInputChange(key)}
                            style={{ width: 200 }}
                        />
                    ))}
                </Space>
            </>
        )
    }

    //主界面表格列
    let mainColumns = []

    //console.log('columns: ', columns);
    //console.log('selectedEntity: ', selectedEntity);

    let mainColumnsJson = columns.reduce((acc, item) => {
        acc[item.value] = item.label;
        return acc;
    }, {});



    //console.log('mainColumnsJson: ', mainColumnsJson);



    for (var x in mainColumnsJson) {
        mainColumns.push({
            title: mainColumnsJson[x],
            dataIndex: x,
            key: x
        })
    }

    mainColumns.push({
        title: '操作',
        dataIndex: 'action',
        key: 'action'
    })


    //自定义操作列渲染
    const targetObject = mainColumns.find(item => item.key === 'action');
    const edit = (record) => {
        mainUpdateForm.setFieldsValue(record);
        updateModalVisibility(1, true);
    }
    const deleteRow = (key) => {
        const newData = mainData.filter((item) => item.id !== key);
        setMainData(newData);

        //TODO Fetch DELETE
        deleteMainData('http://localhost:8080/api/v1/' + selectedEntity + '/id/' + key);
        getMainData('http://localhost:8080/api/v1/' + selectedEntity);

    };

    if (targetObject) {
        targetObject.render = (_, record) => {
            
                return (
                    <>
                        <Space size='middle'>
                            <a href="#" onClick={() => edit(record)}><EditOutlined />编辑</a>
                            <Popconfirm title="确定要删除吗？" onConfirm={() => deleteRow(record.id)}>
                                <a href="#" style={{ color: 'red' }}><DeleteOutlined /> 删除</a>
                            </Popconfirm>
                        </Space>
                    </>
                )
            

        };
    }


    const codeObject = mainColumns.find(item => item.key === 'code');
    if (codeObject) {
        codeObject.render = (_, record) => {
            return (
                <>
                    <a href="#" onClick={() => edit(record)}>{record.code}</a>
                </>
            )
        }
    }

    //console.log('mainColumns: ', mainColumns);




    //对话框
    const [isModalVisible, setIsModalVisible] = React.useState([false, false, false]);

    // 修改第 i 个元素的值
    const updateModalVisibility = (i: number, newValue: boolean) => {
        setIsModalVisible(prevState => {
            // 创建一个新的数组，避免直接修改原数组
            const newArray = [...prevState];
            newArray[i] = newValue; // 修改第 i 个元素
            return newArray;
        });
    };
    const onFinish = (values: any) => {
        console.log('Success:', values);
        postMainData(values, 'http://localhost:8080/api/v1/' + selectedEntity )
        updateModalVisibility(0, false);
        getMainData('http://localhost:8080/api/v1/' + selectedEntity);
    };
    const handleUpdate = (values: any) => {
        console.log('Success:', values);
        putMainData(values, 'http://localhost:8080/api/v1/' + selectedEntity +'/id/' + values.id );
        updateModalVisibility(1, false);
        getMainData('http://localhost:8080/api/v1/' + selectedEntity);
    };

 

    const DynamicPostForm: React.FC = () => {
        const fields = Object.keys(mainColumnsJson);

        return (
            <Form layout="vertical" form={mainPostForm} name='mainPostForm' onFinish={onFinish}>
                {Array.from({ length: Math.ceil(fields.length / 2) }, (_, i) => {
                    const rowFields = fields.slice(i * 2, i * 2 + 2);
                    return (
                        <Row key={i} gutter={16}>
                            {rowFields.map((field) => (
                                <Col span={12} key={field}>
                                    <Form.Item label={mainColumnsJson[field]} name={field} rules={[{ required: true }]}>
                                        <Input placeholder={`请输入${mainColumnsJson[field]}`} />
                                    </Form.Item>
                                </Col>
                            ))}
                        </Row>
                    );
                })}
                <Form.Item>
                    <Space style={{ marginLeft: 400, marginTop: 16 }} direction="horizontal">
                        <Button onClick={() => updateModalVisibility(0, false)}>取消</Button>
                        <Button type="primary" htmlType="submit" >提交</Button>
                    </Space>
                </Form.Item>
            </Form>
        );
    };

    const DynamicUpdateForm: React.FC = () => {
        const fields = Object.keys(mainColumnsJson);

        return (
            <Form layout="vertical" form={mainUpdateForm} name='mainUpdateForm' onFinish={handleUpdate}>
                {Array.from({ length: Math.ceil(fields.length / 2) }, (_, i) => {
                    const rowFields = fields.slice(i * 2, i * 2 + 2);
                    return (
                        <Row key={i} gutter={16}>
                            {rowFields.map((field) => (
                                <Col span={12} key={field}>
                                    <Form.Item label={mainColumnsJson[field]} name={field} rules={[{ required: true }]}>
                                        <Input placeholder={`请输入${mainColumnsJson[field]}`} />
                                    </Form.Item>
                                </Col>
                            ))}
                        </Row>
                    );
                })}
                <Form.Item>
                    <Space style={{ marginLeft: 400, marginTop: 16 }} direction="horizontal">
                        <Button onClick={() => updateModalVisibility(1, false)}>取消</Button>
                        <Button type="primary" htmlType="submit" >提交</Button>
                    </Space>
                </Form.Item>
            </Form>
        );
    };







   



    return (
        <>
            {contextHolder}

            <div style={{ marginTop: 20, marginLeft: 20 }}>
                <Space size='large'>
                    <SearchInput />
                    <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                        搜索
                    </Button>
                    <Button icon={<ReloadOutlined />} onClick={resetSearch}>
                        重置
                    </Button>
                    <Button type="primary" onClick={() => updateModalVisibility(0, true)}>
                        + 新增
                    </Button>
                    {exportable && <Button onClick={handleExport} icon={<DownloadOutlined />} type="primary" style={{}}>
                        导出
                    </Button>}
                    {/* 主界面新增对话框 一个Form*/}
                    <MyModal open={isModalVisible[0]} onCancel={() => updateModalVisibility(0, false)}>
                        <DynamicPostForm />
                    </MyModal>
                    {/* 更新表单 */}
                    <MyModal open={isModalVisible[1]} onCancel={() => updateModalVisibility(1, false)}>
                        <DynamicUpdateForm />
                    </MyModal>

                </Space>
                <Divider />
                <Row>
                    <Table dataSource={mainData.slice((currentPage - 1) * pageSize, currentPage * pageSize)} columns={mainColumns} style={{ width: '100%' }} pagination={{
                        total: mainData.length,
                        current: currentPage,
                        pageSize: pageSize,
                        onChange: (page) => {
                            setCurrentPage(page);
                        },
                    }}></Table>
                </Row>
            </div>
        </>
    )

}

UniversalTable.displayName = '通用表格'
export default UniversalTable;